<template>
  <div >
    <a-cascader
      ref="fieldSelector"
      v-model:value="selecedField"
      size="small"
      placeholder="请选择字段"
      :options="options"
      change-on-select
      @change="handleChange"
      >
    </a-cascader>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, Ref, ref, unref, defineProps, watch, defineExpose, defineEmits , computed} from 'vue';

const fieldSelector = ref();
const selecedField: Ref = ref('');

// 定义组件接收的参数
const props = defineProps({
  body: Object,
  value: String,
});

const emits = defineEmits(['change']);

watch(
  () => props.value,
  (val) => {
    selecedField.value = val && val.split('.')  || []
  },
  { deep: true, immediate: true }
);

const options = computed(() => {
  const tree = [];
  const genTree = (body, list) => {
    if (body.properties) {
      for(let prop in body.properties) {
        const node = {
          label: prop,
          value: prop,
          dataType: body.properties[prop].type
        }
        list.push(node)
        if (body.properties[prop].properties) {
          node.children = []
          genTree(body.properties[prop], node.children)
        }
      }
    }
  }
  genTree(props.body, tree)
  return tree;
});


// 选择组件后获取组件值
function handleChange(e){
  const checkedNodes =  fieldSelector.value.getCheckedNodes();
  const data = checkedNodes[0].data || {} 
  emits('change', e, data.dataType);
}

</script>

<style scoped lang="less">
:deep(.a-cascader) {
  width: 100%;
}
</style>